#    Tichy
#
#    copyright 2008 Guillaume Chereau (charlie137@gmail.com)
#
#    This file is part of Tichy.
#
#    Tichy is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Tichy is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Tichy.  If not, see <http://www.gnu.org/licenses/>.


from label import Label
from tichy.tasklet import Tasklet
from tichy.text import Text
import tichy.key
from geo import Vect
import wrap


class Edit(Label):
    """A label that can also be edited"""

    def __init__(self, parent, item=None, **kargs):
        assert item is not None
        super(Edit, self).__init__(parent, text=item.value, item=item, **kargs)
        self.cursor_pos = len(item.value)

    def key_down(self, key):
        if key.key == tichy.key.K_BACKSPACE:
            if self.cursor_pos == 0:
                return
            self.item.value = "%s%s" % (self.item.value[:self.cursor_pos-1],
                                        self.item.value[self.cursor_pos:])
            self.cursor_pos -= 1
        elif key.key == tichy.key.K_RETURN:
            self.insert_text('\n')
        elif key.key == tichy.key.K_LEFT:
            if self.cursor_pos == 0:
                return
            self.cursor_pos -= 1
        elif key.key == tichy.key.K_RIGHT:
            if self.cursor_pos == len(self.text):
                return
            self.cursor_pos += 1
        elif key.key == tichy.key.K_UP:
            print "Not done yet"
        elif key.key == tichy.key.K_DOWN:
            print "Not done yet"
        elif key.unicode:
            self.insert_text(key.unicode)
        self.text = self.item.value
        return True

    def insert_text(self, text):
        self.item.value = "%s%s%s" % (self.item.value[:self.cursor_pos],
                                      text,
                                      self.item.value[self.cursor_pos:])
        self.cursor_pos += 1

    def draw(self, painter):
        # Button.draw(self, painter)
        super(Edit, self).draw(painter)
        text = self.item.value
        if not text:
            return
        painter.move(Vect(8, 8))
        color = self.style.font_color or (255, 255, 255)
        wrap.draw(painter, text, self.font, color, self.size.x - 16,
                  cursor_pos=self.cursor_pos)
        painter.umove(Vect(8, 8))
